package com.baizhi.gateway.filter;/*
2023/7/18
    */

import cn.hutool.core.util.StrUtil;
import com.baizhi.common.exception.IllUsernameOrPwdException;
import com.baizhi.util.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
@Component
public class RequiredJWTGatewayFilterFactory extends AbstractGatewayFilterFactory<RequiredJWTGatewayFilterFactory.Config> {
    public RequiredJWTGatewayFilterFactory(){
        super(RequiredJWTGatewayFilterFactory.Config.class);
    }
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("required");
    }
    @Override
    public GatewayFilter apply(RequiredJWTGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //1.从请求路径中获取到token信息   xxx?key1=value1&key2=value2
                String token = exchange.getRequest().getQueryParams().getFirst("token");
                if(StrUtil.isEmpty(token)){
                    throw new IllUsernameOrPwdException("没有token信息！");
                }
                //2.判断token的值是否正常
                JwtUtils.verify(token);
                //3.有值就放行
                return chain.filter(exchange);
            }
        };
    }

    public static class Config {
        private boolean required;
        public Config() {
        }

        public boolean isRequired() {
            return required;
        }

        public void setRequired(boolean required) {
            this.required = required;
        }
    }
}
